<?php

namespace JsonLowCode\Form\Abstract;

use Closure;
use JsonSerializable;
use JsonLowCode\Schema;
use JsonLowCode\UI\FormField;
use JsonLowCode\Form;
use JsonLowCode\Support\Js;

/**
 *
 */
abstract class CustomAbstract implements JsonSerializable
{
    protected Form $form;
    protected string $field;
    protected mixed $label;
    protected mixed $defaultValue = null;
    protected mixed $rule = null;
    protected FormField $formField;
    protected string|array $bindField = "";
    protected ?Schema $element = null;

    use Form\Traits\HasBooted;

    /**
     * @param string|array $field
     * @param mixed $label
     * @param Form $form
     */
    public function __construct(Form $form, string|array $field, mixed $label = null)
    {
        $this->field = $field;
        $this->label = $label;
        $this->form = $form;
        $bindKey = $this->form->getBindKey();
        if (is_string($field)){
            $this->bindField = Js::this($bindKey.".".$this->field);
        }else{
            $this->bindField = array_map(function ($item) use ($bindKey) {
                return Js::this($bindKey.".".$item);
            },$field);
        }
        $this->formField = new FormField($label);
        $this->booted();
    }

    /**
     * 设置默认值
     * @param mixed $value
     * @return $this
     */
    public function defaultValue(mixed $value = null): static
    {
        $this->defaultValue = $value;
        $this->form->setFieldValue($this->field, $value);
        $this->element->prop("defaultValue",$value);
        return $this;
    }

    /**
     * 帮助提示信息
     * @param string|Schema $help
     * @return $this
     */
    public function help(string|Schema $help): static
    {
        $this->formField->help($help);
        return $this;
    }

    /**
     * 帮助提示颜色信息
     * @param string $helpColor
     * @return $this
     */
    public function helpColor(string $helpColor): static
    {
        $this->formField->helpColor($helpColor);
        return $this;
    }

    /**
     * 设置FormField
     * @param Closure|null $closure
     * @return $this
     */
    public function formField(Closure $closure = null): static
    {
        !is_null($closure)&&call_user_func($closure, $this->formField);
        return $this;
    }

    /**
     * 设置FormField
     * @param Closure|null $closure
     * @return $this
     */
    public function element(Closure $closure = null): static
    {
        !is_null($closure)&&call_user_func($closure, $this->element);
        return $this;
    }


    /**
     * @return array
     */
    public function getFieldParams(): array
    {
        return [
            $this->field => JSExpression($this->bindField)
        ];
    }


    /**
     * @return array
     */
    public function jsonSerialize(): array
    {
        $this->render();
        $this->formField->children($this->element);
        return$this->formField->jsonSerialize();
    }
}
